using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using YooAsset;

public class ResMgr : UnitySingleton<ResMgr>
{
    public const string DefaultPackage = "DefaultPackage";
    public const string AssetsPackageRoot = "Assets/Game/AssetsPacakge/";
    public void Init() {
        
    }

    // Package + 资源的路径;
    public AssetHandle LoadAssetAsync<T>(string assetPath, string packageName = null) where T : UnityEngine.Object
    {
        assetPath = Path.Combine(AssetsPackageRoot, assetPath);
        ResourcePackage package = null;
        if (packageName == null) {
            AssetHandle handle = YooAssets.LoadAssetAsync<T>(assetPath);
            return handle;
        }

        package = YooAssets.TryGetPackage(packageName);
        if (package == null) {
            return null;
        }

        return package.LoadAssetAsync<T>(assetPath);
    }

    public SceneHandle LoadSceneAsync(string scenePath, string packageName = null)
    {
        scenePath = Path.Combine(AssetsPackageRoot, scenePath);

        ResourcePackage package = null;

        if (packageName == null) {
            packageName = DefaultPackage;
        }

        package = YooAssets.TryGetPackage(packageName);
        if (package == null) {
            return null;
        }


        return package.LoadSceneAsync(scenePath);
    }

    public T LoadAssetSync<T>(string assetPath, string packageName = null) where T : UnityEngine.Object
    {
        assetPath = Path.Combine(AssetsPackageRoot, assetPath);

        ResourcePackage package = null;
        T assetObject = null;
        AssetHandle handle = null;

        if (packageName == null)
        {
            handle = YooAssets.LoadAssetSync<T>(assetPath);
            if (handle != null) {
                assetObject = handle.AssetObject as T;
                handle.Dispose();
            }
            
            return assetObject;
        }

        package = YooAssets.TryGetPackage(packageName);
        if (package == null) {
            return null;
        }

        handle = package.LoadAssetSync<T>(assetPath);
        if (handle != null)
        {
            assetObject = handle.AssetObject as T;
            handle.Dispose();
        }

        return assetObject;
    }

    public void UnloadUnusedAssets(string packageName) {
        if (packageName == null) {
            packageName = DefaultPackage;
        }

        ResourcePackage package = null;
        package = YooAssets.TryGetPackage(packageName);
        if (package == null) {
            return;
        }

        package.UnloadUnusedAssetsAsync();
    } 
}
